package com.simple.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class TaskExecutorConfig {
	private @Value("${thread.corePoolRatio:0.8}") double corePoolRatio;
	private @Value("${thread.maxPoolRatio:0.5}") double maxPoolRatio;
	
	@Bean("threadTaskExecutor")
	public ThreadPoolTaskExecutor taskExecutor() {
	        
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        int processNum = Runtime.getRuntime().availableProcessors(); // 获取的是cpu核心线程数也就是计算资源
        int corePoolSize = (int) (processNum / corePoolRatio);
        int maxPoolSize = (int) (processNum / maxPoolRatio);
        int queueCapacity = maxPoolSize*2;
        // 设置核心线程数-在不超时情况下，保持活跃的最少线程数
        executor.setCorePoolSize(corePoolSize);
        // 设置最大线程数-可以创建的最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        // 设置队列容量
        executor.setQueueCapacity(queueCapacity);
        // 设置线程活跃时间（秒）
        executor.setKeepAliveSeconds(60);
        // 设置默认线程名称
        executor.setThreadNamePrefix("threadTaskExecutor-");
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        executor.initialize();
        return executor;
    }
}
